Micron Document




JavaScript syntax
part 45/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Functions

A function is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If a user exits the function without a return statement, the value undefined is returned.

function gcd(number1, number2) {
if (isNaN(number1*number2)) throw TypeError("Non-Numeric arguments not allowed.");
number1 = Math.round(number1);
number2 = Math.round(number2);
let difference = number1 - number2;
if (difference === 0) return number1;
return difference > 0 ? gcd(number2, difference) : gcd(number1, -difference);
}
console.log(gcd(60, 40)); // 20
//In the absence of parentheses following the identifier 'gcd' on the RHS of the assignment below,
//'gcd' returns a reference to the function itself without invoking it.
let mygcd = gcd; // mygcd and gcd reference the same function.
console.log(mygcd(60, 40)); // 20

Functions are first class objects and may be assigned to other variables.

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────